package com.example.retrofit_test.RetrofitHttp;

import com.example.retrofit_test.RetrofitExtend.ProgressListener;
import com.example.retrofit_test.RetrofitExtend.ProgressResponseBody;
import com.example.retrofit_test.RetrofitExtend.StringConverterFactory;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by xu on 2017/2/27.
 */

public class HttpHelper {
    //private static final String BASE_URL = "http://lnwcjy.com/api/";
    private static final String BASE_URL = "http://www.google.com/";
    private static final int TIME = 35;

    private static final OkHttpClient client = new OkHttpClient.Builder()
            .connectTimeout(TIME, TimeUnit.SECONDS)
            .readTimeout(TIME, TimeUnit.SECONDS)
            .writeTimeout(TIME, TimeUnit.SECONDS)
            .build();


    private static Retrofit getStringRetrofit(){
        return new Retrofit.Builder()
                .client(client)
                .baseUrl(BASE_URL).addConverterFactory(StringConverterFactory.create()).build();
    }

    private static Retrofit getJsonRetrofit(){
        return new Retrofit.Builder()
                .client(client)
                .baseUrl(BASE_URL).addConverterFactory(GsonConverterFactory.create()).build();
    }

    private static Retrofit getUpDownRetrofit(){
        return new Retrofit.Builder().client(client).baseUrl(BASE_URL).addConverterFactory(GsonConverterFactory.create()).build();
    }

    private static Retrofit getUpDownRetrofit(final ProgressListener listener){
        OkHttpClient newClient = client.newBuilder().addNetworkInterceptor(new Interceptor() {
                @Override
                public Response intercept(Chain chain) throws IOException {
                    okhttp3.Response orginalResponse = chain.proceed(chain.request());
                    return orginalResponse.newBuilder().body(new ProgressResponseBody(orginalResponse.body(), listener)).build();
                }
            }).build();
        return new Retrofit.Builder().client(newClient).baseUrl(BASE_URL).addConverterFactory(GsonConverterFactory.create()).build();
    }


    public static RequestStringService getStringService(){
        return getStringRetrofit().create(RequestStringService.class);
    }

    public static RequestJsonService getJsonService(){
        return getJsonRetrofit().create(RequestJsonService.class);
    }

    public static FileUploadService getFileUpService(){
        return getJsonRetrofit().create(FileUploadService.class);
    }

    public static FileDownloadService getFileDownService(){
        return getUpDownRetrofit().create(FileDownloadService.class);
    }

    public static FileDownloadService getFileDownService(ProgressListener listener){
        return getUpDownRetrofit(listener).create(FileDownloadService.class);
    }
}
